package com.pet.service.impl;

import com.pet.mapper.PetMapper;
import com.pet.pojo.PageResult;
import com.pet.pojo.Pet;
import com.pet.pojo.PetQueryParam;
import com.pet.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 宠物服务实现类
 */
@Service
public class PetServiceImpl implements PetService {
    
    @Autowired
    private PetMapper petMapper;
    
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public PageResult<Pet> queryPetList(PetQueryParam param) {
        // 查询总记录数
        Long total = petMapper.selectPetCount(param);
        
        // 如果总记录数为0，直接返回空结果
        if (total == 0) {
            return new PageResult<>(0L, List.of(), 0, param.getPageNum(), param.getPageSize());
        }
        
        // 查询当前页数据
        List<Pet> records = petMapper.selectPetList(param);
        
        // 计算总页数
        int pages = (int) Math.ceil((double) total / param.getPageSize());
        
        // 返回分页结果
        return new PageResult<>(total, records, pages, param.getPageNum(), param.getPageSize());
    }
    
    @Override
    public List<Pet> getAllPets() {
        return petMapper.selectAll();
    }
    
    @Override
    public List<Pet> getPetsByCondition(String type, String age, String gender, String location) {
        return petMapper.selectByCondition(type, age, gender, location);
    }
    
    @Override
    public Pet getPetById(Long id) {
        return petMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public boolean addPet(Pet pet) {
        // 设置创建时间和更新时间
        String now = LocalDateTime.now().format(formatter);
        pet.setCreateTime(now);
        pet.setUpdateTime(now);
        
        // 默认设置为待领养状态
        if (pet.getStatus() == null) {
            pet.setStatus(0);
        }
        
        return petMapper.insert(pet) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePet(Pet pet) {
        // 设置更新时间
        pet.setUpdateTime(LocalDateTime.now().format(formatter));
        return petMapper.update(pet) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePetStatus(Long id, Integer status) {
        return petMapper.updateStatus(id, status) > 0;
    }
    
    @Override
    @Transactional
    public boolean deletePet(Long id) {
        return petMapper.deleteById(id) > 0;
    }
} 